<route lang="json5">
{
  style: {
    navigationBarTitleText: '我的设备',
    navigationBarBackgroundColor: '#FFFFFF',
  },
}
</route>

<template>
  <navbar text="我的设备" />
  <view class="scroll">
    <view class="public-page" :style="{ height: `calc(100vh - ${safeAreaInsets?.top}px - 44px)` }">
      <view class="public-background">
        <scroll @scrollChange="scrollChange">
          <view class="public-height"></view>
          <view class="list" v-for="(item, index) in deviceList" :key="index">
            <view class="title">
              <text class="sn">
                SN：
                <text :selectable="item.sn ? true : false">
                  {{ item.sn || '--' }}
                </text>
              </text>
              <uv-text
                align="right"
                :color="item.monitor === 1 ? '#ff6a8e' : item.monitor === 2 ? '#f9ae3d' : '#666666'"
                size="26rpx"
                :text="item.monitor === 1 ? '监测中' : item.monitor === 2 ? '上传数据中' : '未监测'"
              ></uv-text>
            </view>
            <view class="content">
              <view>
                <view class="header-font">
                  设备名称：
                  <text class="info ml-16">{{ item.deviceName || '--' }}</text>
                </view>
                <text class="header-font">
                  设备类型：
                  <text class="info ml-16">{{ item.deviceType || '--' }}</text>
                </text>
                <text class="header-font">
                  设备戴机时长：
                  <text class="info ml-16">
                    {{ item.recordDays ? getVal(durationGroup, item.recordDays) : '--' }}
                  </text>
                </text>
                <text class="header-font">
                  是否存在预约中的检查单：
                  <text class="info ml-16">{{ item.status === 1 ? '是' : '否' }}</text>
                </text>
              </view>
              <view class="button">
                <wd-button v-if="isLogin" size="small" plain @click="unbind(item)">
                  <text>解除绑定</text>
                  <wd-icon
                    name="link-unlink"
                    size="26rpx"
                    custom-style="position: relative;top: 2rpx;"
                  ></wd-icon>
                </wd-button>
              </view>
            </view>
          </view>
        </scroll>
      </view>
    </view>
  </view>
</template>

<script lang="js" setup>
// 获取屏幕边界到安全区域距离
import navbar from '@/components/navbar'
import useScan from '@/pages/home/method/useScan'
import scroll from '@/components/scrollView'
import { getDevices, unbindDevice, getExamStatus } from '@/service/index/default'
import { isLoginEd, getUser } from '@/utils/publicMethods'
import { setSn } from '@/utils/publicMethods'
import { durationGroup, getVal } from '@/utils/params'
const { safeAreaInsets } = uni.getWindowInfo()
const { GetWxUrlParam } = useScan()
const deviceList = ref([{}])

const userInfo_ = ref({})
const isLogin = ref(false)
onShow(() => {
  initData()
})

const initData = () => {
  isLogin.value = isLoginEd()
  deviceList.value = [{}]
  if (!isLogin.value) {
    userInfo_.value = {}
    uni.showToast({
      title: '请前往登录',
      icon: 'none',
    })
    setTimeout(() => {
      const pages = getCurrentPages()
      if (pages.length > 1) {
        uni.navigateBack()
      } else {
        uni.switchTab({
          url: '/pages/home/index',
        })
      }
    }, 2000)
    return
  }
  userInfo_.value = getUser()
  getDevices_()
}

// 扫码绑定
const scanCode = (item) => {
  uni.scanCode({
    barCodeInput: true,
    success: (res) => {
      const params = GetWxUrlParam(res?.result)
      if (!params?.sn && !params?.type) {
        uni.showToast({
          title: '未查询到有效参数',
          icon: 'none',
        })
        return false
      }
      uni.reLaunch(
        {
          url: `/pages/home/index?type=device&sn=${params.sn}&name=${params.name}&model=${params.model}`,
        },
        1000,
      )
    },
    fail: (err) => {
      console.log('扫描失败：', err)
    },
  })
}

// 解除绑定
const unbind = (item) => {
  if (item?.monitor === 1) {
    uni.showToast({
      title: `当前存在监测中的检查单，不可解绑`,
      icon: 'none',
    })
    return false
  }
  if (item?.monitor === 2) {
    uni.showToast({
      title: `当前存在上传中的检查单，不可解绑`,
      icon: 'none',
    })
    return false
  }
  if (item?.status === 1) {
    uni.showToast({
      title: `当前存在预约中的检查单，不可解绑`,
      icon: 'none',
    })
    return false
  }
  uni.showModal({
    title: '提示',
    content: '解绑后需要重新预约登记，确认解除绑定吗？',
    showCancel: true,
    confirmColor: '#e50038',
    cancelColor: '#999999',
    success: (res) => {
      if (res.confirm) {
        unbindDevice_(item.sn)
      }
    },
  })
}

// 获取绑定设备列表
const getDevices_ = async () => {
  const { data, code, error } = await getDevices({ userId: userInfo_.value.userId })
  if (code !== 200) {
    uni.showToast({
      title: `${error}`,
      icon: 'none',
    })
    return false
  }
  deviceList.value = data
}

// 解除绑定
const unbindDevice_ = async (sn) => {
  const { data, code, error } = await unbindDevice({ userId: userInfo_.value.userId, sn })
  if (code !== 200) {
    uni.showToast({
      title: `${error}`,
      icon: 'none',
    })
    return false
  }
  uni.showToast({
    title: `解绑成功！`,
    icon: 'success',
  })
  deviceList.value = []
  setSn('')
  setTimeout(() => {
    uni.navigateBack()
  }, 2000)
}
// 分享至好友/群聊
onShareAppMessage((res) => {
  return {
    title: '我的设备',
    path: getCurrentPages()[0].$page.fullPath,
    success: (res) => {},
    fail: (res) => {},
  }
})

const scrollChange = () => {
  initData()
}
</script>

<style lang="scss" scoped>
.list {
  margin-bottom: 20rpx;
  background: #ffffff;
  border-radius: 20rpx 20rpx;
  .title {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
    padding: 24rpx 30rpx;
    background: linear-gradient(180deg, #eef5fd 0%, #dfecf6 100%);
    border-radius: 20rpx 20rpx 0rpx 0rpx;
    .sn {
      font-size: 30rpx;
      color: #000000;
    }
  }
  .content {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    padding: 20rpx 30rpx;

    .header-font {
      display: inline-block;
      width: 100%;
      font-family:
        PingFangSC,
        PingFang SC;
      font-size: 26rpx;
      font-weight: 500;
      line-height: 50rpx;
      color: #000000;
    }
    .info {
      margin-left: 10rpx;
      font-size: 26rpx;
      line-height: 50rpx;
      color: #666666;
    }
    .info-font {
      padding: 0 8rpx;
      margin-bottom: 16rpx;
      font-size: 26rpx;
      line-height: 36rpx;
      color: #666666;
      text-indent: 1.5rem;
    }
    .button {
      margin-top: 10rpx;
      text-align: right;
      :deep(.is-plain) {
        border: none;
      }
      :deep(.is-small) {
        padding: 4rpx 28rpx;
        size: 26rpx;
      }
      :deep(.is-info) {
        color: #ffffff;
        background: #999999;
      }
    }
  }
}
</style>
